package cnt5106.p2p.common;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.net.SocketAddress;

import cnt5106.p2p.common.protocol.Message;

public class Logger {

	private StringBuffer sb;
	private BufferedWriter bw;
	private FileWriter fw;

	public Logger(String logPath) {
		sb = new StringBuffer();
		try {
			fw = new FileWriter(logPath);
			bw = new BufferedWriter(fw);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void addLog(String name, SocketAddress local, boolean isSent, SocketAddress remote, Message msg) {
		String log = logMessage(name, local, isSent, remote, msg);
		System.out.println("test: " + log);
		sb.append(log + "\n");
	}

	public String logMessage(String name, SocketAddress local, boolean isSent, SocketAddress remote, Message msg) {
		return "[" + name + ": " + local + "]\n" + (isSent ? "Sent to " : "Received from") + remote + ": " + msg;
	}
	
	
	public void writeLog() {
		try {
			bw.write(sb.toString());
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void printLog() {
		System.out.println(sb);
	}

	public static void main(String[] args) {

//		Logger logger = new Logger("log.txt");
//		logger.addLog(t1);
//		logger.addLog(t2);
//		logger.addLog(t3);
//		logger.addLog(t5);

//		logger.writeLog();
	}
}
